<?php

class WeixinAction extends Action{
        public function _initialize()
        {
            import('ORG.Net.Session');
        }

        public function index(){
            //测试
            ob_clean();
            if ($_GET['echostr']) { 
                echo $_GET['echostr'];
                exit;
            }
            
            import('@.ORG.Net.Wechat');
            $options = array(
                'token' => 'token',
            );
            $Wechat = new Wechat($options);
            //exit();
            //回复变量声明
            $content = null;
            $data = null;
            //信息提示
            $type = $Wechat->getRev()->getRevType();

            $openid = $Wechat->getRevFrom();

            //看数据库里有没有这条数据,如果没有，新增一条数据
            sleep(1);
            $this->getUserInfo($openid);
            $userModel = D('User');
            $scanModel = M('scan'); 
            switch ($type) {
            case Wechat::MSGTYPE_TEXT:
            $content = $Wechat->getRevContent();
            if($content=='光际测试'){
                $eventInfo['event'] = 'subscribe';
                $eventInfo['key'] = '1_3';
                
            }else{  
            $keyWords = M('key_word')->where(array('special'=>'subscribe'))->select();
            foreach($keyWords as $k=>$val){
                if($content == $val['keyword']){
                    // $this->sendCustom($openid, $val['value'], 'text');
                    $Wechat->text($val['value'])->reply();
                }
            }

            }
            case Wechat::MSGTYPE_EVENT:
            if(!$eventInfo){
                $eventInfo = $Wechat->getRev()->getRevEvent();
            }

            }


             if ($eventInfo['event'] == 'subscribe'){
                $str = "感谢您关注青秀万达广场";
                $this->sendCustom($openid,$str,'text');
                $url2 = "http://game.guangjixinxi.com/nnqxwdpk/Mobile?wecha_id=11";
                $this->sendCustom($openid, "跑酷活动正在火热进行   <a href='".$url2."'>查看活动</a>", 'text');
             }
            

            }


      
        

        /**
         * 根据openid，获取用户基本信息并写入user表
         */
        public function getUserInfo($openid){

            $userModel = D('wxuser');
            $map = array();
            $map['openid'] = $openid;
             
            $exist = $userModel->where($map)->find();
            if (!$exist || (empty($exist['nickname']) && empty($exist['imgurl']))) {
                $token = $this->getToken2();
                // dump($token);die;
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
                $result = $this->httpGet($url);
                $userInfo = json_decode($result, true);
                // dump($userInfo);exit();
                if($userInfo['errcode']=='40001' || $userInfo['errcode']=='40003'){
                    M('Token')->where(array('id'=>'1'))->setField('accessTime',0);
                    return $this->getUserInfo($openid);

                }
                $userInfo['imgurl'] = str_replace("http://wx.qlogo.cn/mmopen/", "", $userInfo['headimgurl']);
                $userInfo['nickname'] = $userInfo['nickname'];
                $userInfo['imgurl'] = $_GET['headimgurl'];
                $userInfo['sex'] = $_GET['sex'];
                $userInfo['province'] = $_GET['province'];
                $userInfo['city'] = $_GET['city'];
                $userInfo['country'] = $_GET['country'];
                $userModel->data($userInfo)->add();
                

            }
        }
    

        /**
         * 获取token
         */
        public function getToken2(){
            $con = mysql_connect("10.66.136.168:3306", "gjxx", "gjxx0okm");
            mysql_select_db("jlHotel", $con);
            $result = mysql_query("SELECT * FROM jl_wechat_plat where id=1");
            while ($row = mysql_fetch_array($result)) {
                $token = $row['accessToken'];
                $tokenTime = $row['accessTime'];
                $appId=$row['appId'];
                $appSecret=$row['appSecret'];
            }
            if ($tokenTime < time()) {
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
                $res = json_decode($this->httpGet($url));
                $access_token = $res->access_token;
                if ($access_token) {
                    $tokenTime = time() + 7000;
                    $token = $access_token;
                    //把accesstoken写入数据表
                    mysql_query("UPDATE gjxx_wechat_plat SET accessToken='" . $token . "',  accessTime='" . $tokenTime . "' WHERE appId='" . $appId . "'");
                }
            }
            return $token;
    }
       

        /**
         * 发送客服信息
         */
        public function sendCustom($openid, $val, $type = 'text')
        {
            $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $this->getToken2();

            if ($type == 'text') {
                $data = '{
        "touser":"' . $openid . '",
        "msgtype":"text",
        "text":
        {
             "content":"' . $val . '"
        }
    }';
            } elseif ($type == 'image') {
                $data = '{
        "touser":"' . $openid . '",
        "msgtype":"image",
        "image":
        {
          "media_id":"' . $val . '"
        }
    }';
            }
            $result=$this->httpPost($url, $data);

        }

      


        public function httpPost($url, $data)
        {
            $ch = curl_init();
    // print_r($ch);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            return curl_exec($ch);
        }


        private function http_post($url, $param, $post_file = false)
        {
            $oCurl = curl_init();
            if (stripos($url, "https://") !== FALSE) {
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            }
            if (is_string($param) || $post_file) {
                $strPOST = $param;
            } else {
                $aPOST = array();
                foreach ($param as $key => $val) {
                    $aPOST[] = $key . "=" . urlencode($val);
                }
                $strPOST = join("&", $aPOST);
            }
            curl_setopt($oCurl, CURLOPT_URL, $url);
            curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($oCurl, CURLOPT_POST, true);
            curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
            $sContent = curl_exec($oCurl);
            $aStatus = curl_getinfo($oCurl);
            curl_close($oCurl);
            if (intval($aStatus["http_code"]) == 200) {
                return $sContent;
            } else {
                return false;
            }
        }


        public function httpGet($url)
        {
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);
            return $output;
        }

     

        
        public function sendWithLink($openid,$val){
            $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $this->getToken2();

                $data = '{
        "touser":"'.$openid.'",
        "msgtype":"text",
        "text":
        {
             "content":"' . "$val" . '"
        }
    }';
                $this->httpPost($url, $data);
        }
   

        public function db(){
            $openid="oqHTgsjEOBSe_fs-TPQnJixSPA0Q";
            $appId="wx9d6ce34d0ab6bd64";
            $amount=101;
            $time=time();
            $sign=md5(md5($openid.$amount.$time));
            $url="http://game.guangjixinxi.com/guangjidata/Crm/SendRed/send?openid=$openid&amount=$amount&timeStamp=$time&sign=$sign&activityId=999&sn=TEST&appId=$appId";
            $rs=$this->httpGet($url);
            $rs=json_decode($rs,true);
            dump($rs);
        }



 
}